package com.gexiaobao.pigeon.app.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.widget.ProgressBar
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.gexiaobao.pigeon.R
import me.hgj.jetpackmvvm.base.appContext
import java.util.concurrent.atomic.AtomicInteger

/**
 * @Author      : hxw
 * @Date        : 2023/7/14 13:30
 * @Describe    :
 */
object LoadingUtil {

    /**
     * 记录请求数量，计数
     */
    private val reqCount: AtomicInteger by lazy {
        AtomicInteger()
    }

    /**
     * 用来显示的Dialog
     */
    @SuppressLint("StaticFieldLeak")
//    private var loadingDialog: LoadingDialog? = null
    private var loadingDialog: MaterialDialog? = null

    /**
     * 上一个请求显示loading的context标记
     */
    private var lastFlag: String = ""

    /**
     * 当前请求显示loading的context标记
     */
    private var currentFlag: String = ""

    /**
     * 等待下一次新的请求的时间，可以适当修改
     */
    private const val waitTime: Long = 500L

    /**
     * 用来延时消失
     */
    private val handler: Handler by lazy {
        Handler(Looper.getMainLooper())
    }

    /**
     *  是否准备dismiss
     */
    private var isReadyToDismiss: Boolean = false


    private var mOnDismissListener: DialogInterface.OnDismissListener? = null

    fun setOnDismissListener(listener: DialogInterface.OnDismissListener) {
        this.mOnDismissListener = listener
    }

    /**
     * 建议在页面正在显示，生命周期大于等于onResume时调用，
     * 如
     * if (lifecycle.currentState == Lifecycle.State.RESUMED) {
    LoadingUtil.show(this, text)
    }
     */
    fun show(context: Context, msg: String? = appContext.getString(R.string.loading)) {
        //把当前标记赋值给上一个标志lastFlag
        lastFlag = this.currentFlag
        //获取当前请求显示的标记
        this.currentFlag = context.toString()
        //判断上一个标志和当前页面标志是否一致
        if (currentFlag != lastFlag) {
            //不一致：说明不是同一个页面 ->> 进行dismiss
            if (loadingDialog != null) {
                lastFlag = ""
                reqCount.set(0)
                forceDismiss()
            }
        }
        if (loadingDialog == null) {
            loadingDialog = MaterialDialog(context)
                .cancelable(false)
                .cancelOnTouchOutside(false)
                .cornerRadius(12f)
                .customView(R.layout.layout_custom_progress_dialog_view)
                .lifecycleOwner()
            loadingDialog?.getCustomView()?.run {
                this.findViewById<TextView>(R.id.loading_tips).text = msg
                this.findViewById<ProgressBar>(R.id.progressBar).indeterminateTintList = SettingUtil.getOneColorStateList(context)
            }
        }
        if (!loadingDialog?.isShowing!!) {
            loadingDialog?.show()
            loadingDialog?.setOnDismissListener {
                mOnDismissListener?.onDismiss(it)
            }
        } else {
            //如果在消失前，又来了请求，在handle里就不去消失
            isReadyToDismiss = false
        }
        startReq()
    }

    /**
     *  强制dismiss
     *  在切换页面时、在不是同一个页面时
     *  如在生命周期：onPause
     */
    fun forceDismiss() {
        loadingDialog ?: return
        try {
            if (loadingDialog?.isShowing!!) {
                loadingDialog?.dismiss()
            }
            loadingDialog = null
            isReadyToDismiss = false
            currentFlag = ""
            lastFlag = ""
            mOnDismissListener = null
            reqCount.set(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    fun dismiss(flag: Any) {
        if (TextUtils.equals(currentFlag, flag.toString()) || currentFlag.isEmpty()) {
            endReq()
        }
    }

    //开始计数(可能多个请求)
    private fun startReq() {
        when {
            //当前标志为空，第一次进入此页面，请求数为1
            currentFlag.isEmpty() -> {
                reqCount.set(1)
            }
            //同一个页面，多个请求，请求数自增
            TextUtils.equals(currentFlag, lastFlag) -> {
                reqCount.incrementAndGet()
            }

            else -> {//不同页面，请求数重置为1
                reqCount.set(1)
            }
        }
    }

    //计数
    private fun endReq() {
        when {
            currentFlag.isEmpty() -> {
                reqCount.set(0)
            }
            //同一个页面，请求数自减
            TextUtils.equals(currentFlag, lastFlag) -> {
                reqCount.decrementAndGet()
            }

            else -> {
                reqCount.set(0)
            }
        }
        //请求都结束了，去消失
        if (reqCount.get() <= 0) {
            reqCount.set(0)
            loadNull()
        }
    }


    /**
     * 延时回收
     */
    private fun loadNull() {
        loadingDialog ?: return
        if (isReadyToDismiss) {
            return
        }
        isReadyToDismiss = true
        //500毫秒后结束，解决多个请求同时show和dismiss时dialog闪烁，
        try {
            handler.postDelayed({
                //如果有请求进来，则不消失
                if (isReadyToDismiss && loadingDialog != null && reqCount.get() == 0) {
                    if (loadingDialog?.isShowing!!) {
                        loadingDialog?.dismiss()
                    }
                    loadingDialog = null
                    mOnDismissListener = null
                    currentFlag = ""
                    lastFlag = ""
                    reqCount.set(0)
                    isReadyToDismiss = false
                }
            }, waitTime)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}